package org.sagitta.httprpc.pox.adaptor;

import java.io.IOException;
import java.io.InputStream;

public class POXUtil {
	private static final String ENCODINGUTF8 = "UTF-8";
	private static final String ENCODINGUTF16 = "UTF-16";

	private static boolean hasBOM(byte b0, byte b1, byte b2) {
		return (b0 & 0xFF) == 0xEF && (b1 & 0xFF) == 0xBB && (b2 & 0xFF) == 0xBF;
	}

	private static boolean hasBOMUTF16(byte b0, byte b1) {
		return ((b0 & 0xFF) == 0xFE && (b1 & 0xFF) == 0xFF) || ((b0 & 0xFF) == 0xFF && (b1 & 0xFF) == 0xFE);
	}

	public static byte[] consumeBOM(byte[] data, String encoding) {
		String s = new String(data);
		return consumeBOM(s, encoding).getBytes();
	}

	public static String consumeBOM(String s) {
		return consumeBOM(s, ENCODINGUTF8);
	}

	public static String consumeBOM(String s, String encoding) {
		byte[] b = new byte[3];
		if (ENCODINGUTF8.equalsIgnoreCase(encoding)) {
			if (s.length() > 3) {
				b = s.substring(0, 3).getBytes();
				if (hasBOM(b[0], b[1], b[2])) {
					return s.substring(3);
				} else {
					return s;
				}
			}
		} else if (ENCODINGUTF16.equalsIgnoreCase(encoding)) {
			if (s.length() > 2) {
				b = s.substring(0, 2).getBytes();
				if (hasBOMUTF16(b[0], b[1])) {
					return s.substring(2);
				} else {
					return s;
				}
			}
		}
		return s;
	}

	public static void consumeBOM(InputStream stream) throws IOException {
		consumeBOM(stream, ENCODINGUTF8);
	}

	public static void consumeBOM(InputStream stream, String encoding) throws IOException {
		byte[] b = new byte[3];
		if (ENCODINGUTF8.equalsIgnoreCase(encoding)) {
			int count = stream.read(b, 0, 3);
			if (count == 3 && hasBOM(b[0], b[1], b[2])) {
				return;					
			}
			stream.reset();
		} else if (ENCODINGUTF16.equalsIgnoreCase(encoding)) {
			int count = stream.read(b, 0, 2);
			if (count == 2 && hasBOMUTF16(b[0], b[1])) {
					return;
			}
			stream.reset();
		}
	}

}
